<template>
  <view
    v-if="store.patient.current"
    :class="['archive-wrap', showAddBtn ? 'show-btn' : '']"
  >
    <scroll-view 
      scroll-y
      @scrolltolower="onLoadmore"
      :lower-threshold="100"
      class="scroll-wrap"
    >
    <image
      class="bg-image"
      src="https://ainengli.meilianshuke.com/jkhx/patient/archive-bg.png"
      mode="widthFix"
    />
      <view class="info-wrap">
        <view class="my-archive">我的档案</view>
        <view class="top-right">
          <!-- <image
            @tap="goPatient"
            class="change-patient"
            src="https://ainengli.meilianshuke.com/jkhx/patient/change-patient.png"
          /> -->
          <view @tap="goPatient" class="change-patient">
            <text class="name">{{ store.patient.current?.patientName }}</text>
            <image class="change-icon" src="https://ainengli.meilianshuke.com/jkhx/patient/change-icon.png" />
          </view>
          <image
            @tap="goCenter"
            class="avatar"
            src="https://ainengli.meilianshuke.com/jkhx/patient/my.png"
          />
        </view>
      </view>
      <view class="tab-wrap">
        <view
          v-for="item in tabList"
          :key="item"
          @tap="changeTab(item)"
          :class="[
            'tab-item',
            currentTab === item ? 'active' : 'no-active',
          ]"
        >
          <!-- 未选中背景图 -->
          <image
            class="tab-bg"
            src="https://ainengli.meilianshuke.com/jkhx/patient/no-active-tab.png"
            mode="widthFix"
          />
          <!-- 选中覆盖图 -->
          <image
            v-if="item === currentTab"
            class="tab-active-bg"
            :src="getActiveBg(item)"
            mode="aspectFill"
          />
          <text class="tab-title">{{ item }}</text>
        </view>
      </view>
      <view class="height-wrap" v-if="showAddBtn">
        <GrouthPage
          :patientInfo="store.patient.current"
          :heightDetailList="heightDetailList"
          :topData="topData"
          :geneticHeightData="geneticHeightData"
        />
      </view>
    <view v-if="!hasArchive && currentTab === '生长发育'" class="empty-wrap">
      <NoData :emptyStyle="{height: 197, width: 320}">
        <view class="add-btn" @tap="goCreate">创建档案</view>
      </NoData>
    </view>
    <medicalRecord v-if="currentTab === '就医资料'" :medicalRecordList="medicalRecordList" />
    </scroll-view>
    <com-popup v-if="showPatient" ref="popup" title="切换就诊人" :action="false" :showTitleBorder="true" @close="showPatient = false">
      <view class="lists">
        <view
          v-for="(item, index) in patientList"
          :key="index"
          :class="['item', item.id === store.patient.current.id ? 'active' : '']"
          @tap="selectPatient(item)"
        >
          <view>{{ item?.patientName }}</view>
          <view class="info">
            <text class="gender">{{ item.gender == 1 ? '男' : '女' }}</text>
            <text>{{ item.ageYear > 0 ? item.ageYear + '岁' : '' }}{{ item.ageMonth == 0 && item.ageYear == 0 ? '未满月' : item.ageYear < 18 && item.ageMonth != 0 ? item.ageMonth + '月' : '' }}
            </text>
          </view>
          <image v-show="item.id === store.patient.current.id" src="https://ainengli.meilianshuke.com/jkhx/patient/selected-icon.png" class="selected" />
        </view>
      </view>
    </com-popup>
    <view v-if="showAddBtn" class="fixedBtn" @tap="addHeightWeight">
      <text class="name">记录身高体重</text>
    </view>
  </view>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, computed, watch } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";

import { useStore } from "@/store";
import GrouthPage from "./components/grouth.vue";
import NoData from "./components/no-data.vue";
import medicalRecord from "./components/medical-record.vue";
import { getDetailList, getMedicalRecordList, getPatientBaseInfo } from "@/request/apis/archive";
import { patientGet } from "../patients/patient.api";
const { proxy }: any = getCurrentInstance();
const store = useStore();

const tabList = ref(["生长发育", "就医资料"]);
const patientList = computed(() => store.patient.list);

const showPatient = ref(false);

const heightDetailList = ref([]);
const topData = ref({});
const geneticHeightData = ref([]);
const medicalRecordList = ref([])
const pageInfo = ref({
  page: 1,
  limit: 10,
  hasMore: true,
  loading: false
})

const hasPatient = ref(false);
const hasArchive = ref(true);
const currentTab = ref("生长发育");

const activeBgMap = {
  '生长发育': 'https://ainengli.meilianshuke.com/jkhx/patient/active-tab-left.png',
  '就医资料': 'https://ainengli.meilianshuke.com/jkhx/patient/active-tab-right.png'
}
function getActiveBg(type) {
  return activeBgMap[type]
}

const changeTab = (tab: string) => {
  if (tab === currentTab.value) return;
  currentTab.value = tab;
  if (tab === "就医资料")  {
    getMedicalRecordListById()
  }
};

const goCreate = () => {
	uni.navigateTo({
		url: '/pages/archive/add-archive',
	})
}

const selectPatient = (item: any) => {
  // 切换就诊人
  let params = {
    id: item.id,
  }
  patientGet(params).then((res) => {
    store.setPatientInfo(res)
    showPatient.value = false
    proxy.utils.uni.route.back({ delta: 0 })
  })
}

const showAddBtn = computed(() => {
  return currentTab.value === "生长发育" && hasArchive.value;
});

const addHeightWeight = () => {
  uni.navigateTo({
    url: "/pages/archive/add-height-weight",
  });
};

const getArchiveInfo = () => {
  getPatientBaseInfo({ patientId: store.patient.current?.id }).then((res) => {
    hasArchive.value = !!res.healthRecordExists;
    geneticHeightData.value = sortItems(res.records?.filter((item) =>
      ["genetic_height"].includes(item.code)
    ));
    topData.value = {
      ageMonth: res.recordAgeMonths,
      ageYear: res.recordAgeYears,
      list: sortItems(res.records?.filter((item) =>
        ["height", "weight", "bmi"].includes(item.code)
      ))
    }
  });
};

const goPatient = () => {
  showPatient.value = true
  // uni.navigateTo({
  //   url: "/pages/patients/index",
  // });
};

const goCenter = () => {
  uni.navigateTo({
    url: "/pages/personalCenter/index",
  });
};

watch(
  () => store.patient.current,
  (newVal) => {
    hasPatient.value = !!newVal;
  },
  { deep: true }
);

const sortItems = (items) => {
  // 定义排序顺序
  const sortOrder = {
    height: 1,
    weight: 2,
    bmi: 3,
  };

  return items?.sort((a, b) => {
    // 获取每个对象的排序优先级
    const orderA = sortOrder[a.code] || Infinity;
    const orderB = sortOrder[b.code] || Infinity;

    // 按优先级排序
    return orderA - orderB;
  });
};

const getHeightDetailList = () => {
  if (!store.patient.current?.id || !pageInfo.value['hasMore'] || pageInfo.value['loading']) {
    return;
  }
  pageInfo.value.loading = true
  getDetailList({
    patientId: store.patient.current?.id,
    pageNo: pageInfo.value['page'],
    pageSize: pageInfo.value['limit']
  }).then((res) => {
    pageInfo.value.loading = false
    if (res.list) {
      const list = res.list || []
      const isFirstPage = pageInfo.value.page === 1
      const hasNoMoreData = list.length < pageInfo.value.limit
      const currentList = [...heightDetailList.value]

      pageInfo.value.hasMore = !hasNoMoreData

      const newList = res.list?.map((item, index) => {
        return {
          id: item.id,
          recordDate: item.recordDate,
          createTime: item.createTime,
          ageYear: item.recordAgeYears,
          ageMonth: item.recordAgeMonths,
          items: sortItems(
            item.items?.filter((item) => ['height', 'weight', 'bmi'].includes(item.code))
          )
        }
      })
      heightDetailList.value = isFirstPage ? newList : [...currentList, ...newList]
    } else {
      pageInfo.value.status = 'error'
      pageInfo.value.loading = false
    }
  }).catch(() => {
    pageInfo.value.status = 'error'
    pageInfo.value.loading = false
  }).finally(() => {
    pageInfo.value.loading = false
  });
};

const onLoadmore = () => {
  if (pageInfo.value['hasMore']) {
    pageInfo.value.page++
    getHeightDetailList()
  }
}

const onReset = () => {
  pageInfo.value['loading'] = false
  pageInfo.value['hasMore'] = true
  pageInfo.value['page'] = 1
  // setTimeout(() => {
  //   getHeightDetailList()
  // }, 1000)
}

watch(
  () => store.patient.current?.id,
  () => {
    onReset();
    getArchiveInfo();
    getHeightDetailList();
    getMedicalRecordListById();
  }
);

const getMedicalRecordListById = () => {
  getMedicalRecordList({ patientId: store.patient.current.id }).then(res => {
    medicalRecordList.value = res.records || []
  })
}

onShow((e) => {
  uni.hideTabBar()
  if (!store.patient.current) {
    uni.showModal({
      title: "提示",
      content: "请添加就诊人",
      showCancel: false,
      confirmText: "去添加",
      confirmColor: "#00d1b6",
      success: function (res) {
        proxy.utils.uni.route.go("/pages/patients/addOrDelete?type=add");
      },
    });
  } else {
    onReset();
    getArchiveInfo();
    getHeightDetailList();
    getMedicalRecordListById()
  }
});

onLoad((e) => {});
</script>
<style lang="scss" scoped>
.archive-wrap {
  min-height: 100vh;
  // background-color: #F3F7F8;
  // background-image: url("https://ainengli.meilianshuke.com/jkhx/patient/archive-bg.png");
  // background-repeat: no-repeat;
  // background-size: 100% auto;
  // padding-bottom: calc(202rpx - constant(safe-area-inset-bottom));
  // padding-bottom: calc(202rpx - env(safe-area-inset-bottom));

  .scroll-wrap {
    height: calc(100vh - 130rpx - constant(safe-area-inset-bottom));
    height: calc(100vh - 130rpx - env(safe-area-inset-bottom));
    // background-color: #F3F7F8;
    .bg-image {
      position: absolute;
      z-index: -1;
      width: 100vw;
    }

    .height-wrap {
      position: relative;
      top: -52rpx;
      z-index: 10;
      box-sizing: border-box;
      padding-bottom: 48rpx;
      // background-color: #f3f7f8;
    }

    .empty-wrap {
      padding: 264rpx 96rpx 0;
    }
    
    .info-wrap {
      padding: 38rpx 32rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .my-archive {
        color: #222222;
        font-size: 36rpx;
        font-weight: bold;
      }
      .top-right {
        display: flex;
        gap: 32rpx;
        .change-patient {
          max-width: 180rpx;
          height: 56rpx;
          display: flex;
          align-items: center;
          padding: 0 24rpx;
          background: linear-gradient(to bottom, #f3fffa, #ffffff);
          border-radius: 36rpx;
          // gap: 4rpx;
          border: 2rpx solid #fff;
          .name {
            flex: 1;
            font-size: 22rpx;
            color: #456465;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            text-align: center;
          }
          .change-icon {
            width: 24rpx;
            height: 23rpx;
          }
        }
        .avatar {
          width: 56rpx;
          height: 56rpx;
        }
      }
    }

    .tab-wrap {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: flex-end;
      height: 178rpx;
      position: relative;
      transition: all 0.3s ease-out;
      .tab-item {
        flex: 1;
        margin: 0 6rpx;
        display: flex;
        align-items: flex-end;
        justify-content: center;
        transition: height 0.2s;
        box-sizing: border-box;
        color: #666666;
        transition: all 0.3s ease-out;
      }
      .tab-bg,
      .tab-active-bg {
        position: absolute;
        left: 0;
        bottom: 46rpx;
        width: 100vw;
        height: 164rpx;
        z-index: 0;
      }
      .tab-active-bg {
        z-index: 1;
        height: 178rpx;
        bottom: 0;
      }
      .tab-title {
        position: relative;
        z-index: 2;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 96rpx;
      }
      .tab-item.active .tab-title {
        font-weight: bold;
        position: relative;
        color: #222222;
        font-size: 34rpx;
      }
      .tab-item.active .tab-title::after {
        content: "";
        position: absolute;
        bottom: -24rpx;
        left: 50%;
        width: 44rpx;
        height: 6rpx;
        border-radius: 22rpx;
        background-color: #00D1B6;
        transform: translateX(-50%);
        transition: all 0.3s ease;
      }
      .tab-item.no-active {
        height: 162rpx;
      }
      .tab-item.no-active .tab-title {
        height: 132rpx;
        width: 100%;
        display: flex;
        justify-content: center;
        box-sizing: border-box;
        margin-bottom: 0;
      }
    }
  }
  .fixedBtn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 24rpx 0;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    color: #fff;
    text-align: center;
    background: #fff;
    // border-top: 1rpx solid #e5e6eb;
    z-index: 25;

    .name {
      display: inline-block;
      width: calc(100% - 60rpx);
      padding: 22rpx 0;
      margin: 0 30rpx;
      font-size: 32rpx;
      font-weight: 600;
      background: #00d1b6;
      border-radius: 50rpx;
    }
  }
  .lists {
    padding: 32rpx;
    // max-height: calc(100vh - 200rpx);
    overflow: scroll;
    .item {
      box-sizing: border-box;
      border-radius: 10rpx;
      background: #fafafa;
      // text-align: center;
      display: flex;
      padding: 24rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #222222;
      margin-bottom: 24rpx;
      gap: 32rpx;
      position: relative;
      .selected {
        position: absolute;
        right: 0;
        top: 0;
        width: 45rpx;
        height: 40rpx;
      }
      .info {
        border: 1rpx solid #e5e6eb;
        border-radius: 4rpx;
        background: #fff;
        padding: 8rpx 24rpx;
        font-size: 24rpx;
        color: #666666;
        .gender::after {
          content: '';
          display: inline-block;
          width: 1rpx;
          height: 18rpx;
          // border-radius: 50%;
          background: #666666;
          margin: 0 16rpx;
        }
      }
    }
    .item.active {
      border: 1rpx solid #00D1B6;
      background: rgba(0, 209, 182, 0.10);
    }
    .item:last-child {
      margin-bottom: 0;
    }
  }
}
.add-btn {
  background: #00D1B6;
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
  border-radius: 44rpx;
  margin-top: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
} 
.show-btn {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
